package org.smart.access.config;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.exceptions.PersistenceException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.resource.NoResourceFoundException;

import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(NotLoginException.class)
    public SaResult handle401(NotLoginException e) {
        log.warn("登录验证失败|id={}", StpUtil.getLoginId());
        return SaResult.notLogin();
    }

    @ExceptionHandler(NullPointerException.class)
    public SaResult handleNpe(NullPointerException e) {
        log.error("空指针异常", e);
        return SaResult.get(400, "参数错误", null);
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResponseEntity<String> handle405() {
        return ResponseEntity
                .status(HttpStatus.METHOD_NOT_ALLOWED)
                .body("请求方法不支持");
    }

    @ExceptionHandler(NoResourceFoundException.class) // 404
    public ResponseEntity<String> handle404() {
        return ResponseEntity
                .status(HttpStatus.NOT_FOUND)
                .body("接口不存在");
    }

    @ExceptionHandler
    public SaResult handlerException(Exception e) {
        if ((e instanceof PersistenceException && e.getCause() instanceof SQLIntegrityConstraintViolationException)
                || e instanceof SQLIntegrityConstraintViolationException
                || (e instanceof SQLException && ((SQLException) e).getErrorCode() == 1062)) {
            log.warn("数据已存在|{}", e.getMessage());
            return SaResult.get(501, "数据已存在", null);
        }

        e.printStackTrace();
        log.error(e.getMessage());
        return SaResult.error("后端接口异常，请联系管理员");
    }
}
